package com.example.springboot_shopping.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_shopping.entity.User;
import com.example.springboot_shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    // 查询所有用户
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public User findById(@PathVariable Integer id) {
        return userService.findById(id);
    }

    // 注册用户
    @PostMapping("/register")
    public boolean register(@RequestBody User user) {
        return userService.register(user);
    }

    // 更新用户信息
    @PutMapping
    public boolean update(@RequestBody User user) {
        return userService.update(user);
    }

    // 删除用户（逻辑删除）
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return userService.deleteById(id);
    }

    // 登录（跳转页面示例）
    @GetMapping("/loginPage")
    public ModelAndView loginPage() {
        return new ModelAndView("login");
    }

    // 处理登录请求
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("loginUser", user);
            return "redirect:/home";
        } else {
            return "redirect:/users/loginPage?error=1";
        }
    }

    @GetMapping("/page")
    public Page<User> findByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        return userService.findByPage(pageNum, pageSize);
    }
}